﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows;

namespace University.Workshop.Presentation.ControlWPF
{
    public class NumericTextBox:TextBox
    {
        public TypeTexBox TextBoxType { get; set; }
        public bool CanCut
        {
            set
            {
                if (!value)
                {
                    CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, null, CancelCommand));
                }
            }
        }
        public bool CanPaste
        {
            set
            {
                if (!value)
                {
                    CommandBindings.Add(new CommandBinding(ApplicationCommands.Paste, null, CancelCommand));
                }
            }
        }
        public bool CanCopy
        {
            set
            {
                if (!value)
                {
                    CommandBindings.Add(new CommandBinding(ApplicationCommands.Copy, null, CancelCommand));
                }
            }
        }

        private static void CancelCommand(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = false;
            e.Handled = true;
        }
        
        /// <summary>
        /// Stops the effect of some common keys
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreviewKeyDown(System.Windows.Input.KeyEventArgs e)
        {
            if  (e.Key == Key.Space)
            {
                e.Handled = true;
            }
            base.OnPreviewKeyDown(e);

        }

        /// <summary>
        /// We check whether we are ok
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e)
        {
            string temporalNumber=this.Text+e.Text;
            try
            {
                switch (TextBoxType)
                {
                    case (TypeTexBox.Integer):
                        var q=Convert.ToInt32(temporalNumber);
                        break;
                    case (TypeTexBox.Decimal):
                        e.Handled=temporalNumber.Split(',').Count()>2;
                        Convert.ToDecimal(temporalNumber);
                        break;                        
                }
            }
            catch
            {
                e.Handled = true;
            }
        }

    }
    
    public enum TypeTexBox
    {
        Decimal=0,
        Integer=1
    }
}
